#include "ab32_uart.h"

#define PROTOCAL_UART_NAME       "uart1"

static struct rt_semaphore rx_sem;
static rt_device_t serial;
rt_uint8_t uart1_rx_buff[8];
rt_uint32_t read_data_cnt = 0;
rt_uint8_t read_flag = 0;
rt_thread_t uart1_thread;

static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    rt_sem_release(&rx_sem);
    return RT_EOK;
}

void hw_send(rt_uint8_t *data, rt_uint8_t len)
{
    int ii = 0;
    for(ii = 0; ii < len; ii++)
    {
        rt_device_write(serial, 0, &data[ii], 1);
    }
}

static void serial_thread_entry(void *parameter)
{
    char ch;

    while (1)
    {
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }

        //读出串口的值,进行组包
        // ch = ch + 1;
        // rt_device_write(serial, 0, &ch, 1);
        if(ch == 0x55) //组包的头部,或者中间数据
        {
            read_flag = 1;
        }

        if(read_flag)
        {
            if(read_data_cnt <= 5)
            {
                uart1_rx_buff[read_data_cnt] = ch;
                read_data_cnt++;
            }

            if(read_data_cnt == 6)
            {
                AB32_msgProc(uart1_rx_buff, 6);
                read_data_cnt = 0;
                read_flag = 0;
            } 
        }
    }
}

int ab32_uart1_init(void)
{
    rt_err_t ret = RT_EOK;
    serial = rt_device_find(PROTOCAL_UART_NAME);
    if (!serial)
    {
        rt_kprintf("find uart failed!\n");
        return RT_ERROR;
    }

    /* 初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
    // /* 发送字符串 */
    // rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 创建 serial 线程 */
    uart1_thread = rt_thread_create("serial1", serial_thread_entry, RT_NULL, 1024, 25, 10);
    /* 创建成功则启动线程 */
    if (uart1_thread != RT_NULL)
    {
        rt_thread_startup(uart1_thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    return ret;
}

